/*
 * 上海远境文化传媒有限公司 版权所有
 */
package helper;


import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import play.libs.Codec;

/**
 * 安全码
 */
public class SafeCodeHelper {

    private static final String SAFE_GENERATE_SEED = "idnq073n1adfa00SDFan3a";

    /**
     * 生成一个安全码，确认是我们生成的.
     * @return
     */
    public static String generateSafeCode() {
        String source = RandomStringUtils.randomAlphanumeric(8);

        return getSafeCodeFromSource(source);
    }

    private static String getSafeCodeFromSource(String source) {
        String hexSHA1 = Codec.hexSHA1(source + SAFE_GENERATE_SEED);

        return source + hexSHA1.substring(0, 8);
    }

    public static boolean validSafeCode(String safeCode) {
        if (StringUtils.isBlank(safeCode) || safeCode.length() < 15) {
            return false;
        }
        String source = safeCode.substring(0, 8);

        return safeCode.equals(getSafeCodeFromSource(source));
    }
}
